import numpy

import cv2
from PIL import Image
import numpy as np
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt

def img_paste(img,img2,img3,location):
    #img2 = img2.resize(size, Image.ANTIALIAS)
    r, g, b, a = img2.split()
    img.paste(img2, location, mask=a)

    #img3 = img3.resize((size[0]+2,size[1]+2), Image.ANTIALIAS)
    r, g, b, a = img3.split()
    img.paste(img3, location, mask=a)
    return img


def img_convert_video(video_dir,images):
    fps = 24
    fourcc = cv2.VideoWriter_fourcc('X','2','6','4')  # opencv3.0
    videoWriter = cv2.VideoWriter((video_dir+".mp4"), fourcc, fps, (640,592))

    print('Converting image to video.............')
    for i in range(len(images)):
        frame = cv2.cvtColor(numpy.asarray(images[i]), cv2.COLOR_RGB2BGR)
        videoWriter.write(frame)
    videoWriter.release()
    #command = "ffmpeg -f image2 -i "+img_dir+"/%d.jpg  -vcodec libx264 -r 24 "+video_dir+".mp4"
    #command = "ffmpeg -threads 0  -i %s.mp4 -vcodec libx264 -f mp4 %sa.mp4" % (video_dir, video_dir)
    #command = "ffmpeg -f image2 -i /work/project/deepface/static/img/2019031514465060/%d.jpg  -vcodec libx264 -r 24 13323.mp4"
    #print command
    #os.system(command)
    print('Converting image to video success')


def img_deal(input_img):
    img = cv2.imread(input_img, cv2.IMREAD_UNCHANGED)
    rows, cols, channel = img.shape

    img_new = np.zeros((rows,cols,4),np.uint8)
    img_new[:,:,0:3] = img[:,:,0:3]

    img_circle = np.zeros((rows,cols,1),np.uint8)
    img_circle[:,:,:] = 0
    img_circle = cv2.circle(img_circle,(cols/2,rows/2),min(rows, cols)/2,(255),-1)

    img_new[:,:,3] = img_circle[:,:,0]

    plt.subplot(121), plt.imshow(img_convert(img), cmap='gray'), plt.title('IMG')
    plt.subplot(122), plt.imshow(img_convert(img_new), cmap='gray'), plt.title('IMG_NEW')
    return img_new


def img_convert(cv2_img):
    if len(cv2_img.shape) == 2:
        return cv2_img
    elif len(cv2_img.shape) == 3 and cv2_img.shape[2] == 3:
        b, g, r = cv2.split(cv2_img)
        return cv2.merge((r, g, b))
    elif len(cv2_img.shape) == 3 and cv2_img.shape[2] == 4:
        b, g, r, a = cv2.split(cv2_img)
        return cv2.merge((r, g, b, a))
    else:
        return cv2_img

